package com.woniuxy.voice.service;

import com.baidu.aip.speech.AipSpeech;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class VoiceRecognitionService {

    @Autowired
    private AipSpeech baiduSpeechClient;

    /**
     * 语音识别
     * @param audioData 音频字节数组
     * @param format 音频格式，如"wav"
     * @param sampleRate 采样率，如16000
     * @param options 可选参数
     * @return 识别结果
     */
    public String recognize(byte[] audioData, String format, int sampleRate, Map<String, Object> options) {
        try {
//            options.put("dev_pid", 1537); // 中文普通话
            // 调用语音识别API
            JSONObject response = baiduSpeechClient.asr(audioData, format, sampleRate, (HashMap<String, Object>) options);

            // 解析响应
            if (response.has("result") && !response.getJSONArray("result").isEmpty()) {
                return response.getJSONArray("result").get(0).toString();
            }
            return "识别失败";
        }catch (Exception e) {
            // 记录日志或返回更友好的错误信息
            e.printStackTrace();
            return "语音识别服务异常，请稍后再试";
        }
    }
}